﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Globalization;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics;

namespace Hallenberg.Core.Globalization
{
    [SuppressMessage("Microsoft.Design", "CA1063:ImplementIDisposableCorrectly")]
    public class ChangeThreadCulture : IDisposable
    {
        private readonly string previousCultureName;
        private readonly string previousUICultureName;
        
        public ChangeThreadCulture(string languageName)
        {
            Debug.Assert(!string.IsNullOrEmpty(languageName));
            if (string.IsNullOrEmpty(languageName))
            {
                throw new ArgumentNullException("languageName");
            }

            if (CultureInfo.GetCultures(CultureTypes.AllCultures).FirstOrDefault(ci => ci.Name == languageName) == null)
            {
                throw new ArgumentException("The provided language name does not exist", "languageName");
            }

            previousCultureName = Thread.CurrentThread.CurrentCulture.Name;
            previousUICultureName = Thread.CurrentThread.CurrentUICulture.Name;

            Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(languageName);
            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(languageName);
        }

        [SuppressMessage("Microsoft.Design", "CA1063:ImplementIDisposableCorrectly")]
        public void Dispose()
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(previousCultureName);
            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(previousUICultureName);

            GC.SuppressFinalize(this);
        }
    }
}
